<template>
  <a-drawer :open="true" :title="`${item ? '编辑' : '添加'}品牌`" @close="onClose">
    <a-form ref="formRef" :model="formState" layout="vertical" :rules="rules">

      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <DictSelect code="BRAND_CATEGORY" v-model:value="formState.category" />
      </a-form-item>
      <a-form-item label="热门" name="hot">
        <a-radio-group v-model:value="formState.hot">
          <a-radio :value="true">是</a-radio>
          <a-radio :value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="图标" name="logo">
        <a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card" :before-upload="beforeUpload">
          <div v-if="fileList.length == 0">
            <plus-outlined></plus-outlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="toSave" :loading="saving">保存</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script setup>
import { reactive, onMounted, ref } from 'vue'
import { saveBrand } from '@/api/brand';
import { message } from 'ant-design-vue'
import { confirm } from '@/mixin'
import { upload } from '@/api/att'
import DictSelect from './DictSelect.vue';

const props = defineProps(['item'])
const emit = defineEmits(['close', 'saved'])

const rules = {

  name: [
    { required: true, message: '请输入品牌名称' }
  ],
  group: [
    { required: true, message: '请选择品牌类型' }
  ],
}

const formRef = ref(null)
const formState = reactive({})
const saving = ref(false)
const fileList = ref([])

onMounted(() => {
  parseItem()
})

const parseItem = () => {
  const it = props.item
  if (it) {

    formState.name = it.name
    formState.category = it.category
    formState.hot = it.hot
  } else {
    formState.name = null
    formState.category = null
    formState.hot = false
  }
}

const onClose = () => {
  emit('close')
}
const beforeUpload = () => {
  return false;
}

const toSave = () => {
  formRef.value.validate().then(values => {

    if (fileList.value.length == 0) {
      message.warn('请选择品牌LOGO图标')
      return
    }

    confirm('您确定要保存品牌信息吗?', async () => {
      if (props.item) {
        values.id = props.item.id
      }
      saving.value = true

      let file = fileList.value[0].originFileObj
      if (file) {
        const res = await upload(file,'brand')
        if(res.data){
          values.logo = res.data.id
        }
      }
      const res = await saveBrand(values)
      saving.value = false
      if (res.data) {
        message.success('保存成功')
        emit('saved')
      } else {
        message.error('保存失败')
      }
    })
  })
}
</script>

<style lang="less" scoped></style>